// pages/cart/index.js
import {
  getSetting,
  chooseAddress,
  openSetting,
  showModal,
  showToast
} from "../../utils/asyncWx.js";
import regeneratorRuntime from '../../lib/runtime/runtime';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cart: [],
    address: {},
    totalprice: 0,
    totalnum: 0,
    allchecked: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onShow() {

    const cart = wx.getStorageSync("cart")
    const address = wx.getStorageSync("address")
    this.setData({
      cart,
      address
    })
    this.setMoney(cart)
  },
  async handleChooseAddress() {

    try {
      const res1 = await getSetting()
      const scopeAddress = res1.authSetting['scope.address']
      console.log(scopeAddress)
      if (scopeAddress === false) {
        await openSetting()
      }
      let address = await chooseAddress();
      address.all = address.provinceName + address.cityName + address.countyName + address.detailInfo;

      // 5 存入到缓存中
      wx.setStorageSync("address", address);
    } catch (error) {
      console.log(err)
    }
  },
  //点击加号 商品数量加1
  //先用data-传递商品的index 根据index判断是哪个商品需要进行数量增减操作
  //然后用数组的forEach方法遍历到对应的index中的num
  //最后setData完成数量操作 
  //最后要注意的是应当将最新的cart值更新到本地缓存中 否则刷新页面后cart.num的值将返回未更新之前的值
  handleGoodsNumAdd(e) {

    const {
      index
    } = e.currentTarget.dataset
    let cart = this.data.cart
    let num = cart[index].num + 1
    cart.forEach((v, i) => {
      i === index ? v.num = num : ''
    })

    this.setMoney(cart)
  },
  //点击减号 商品数量减一 原理同上面的增加操作一样
  //当商品数量已经为1时继续点击减号 将触发商品的删除事件
  //res.confirm是一个布尔值，调用小程序api后若点击确认返回为true 取消则为false
  async handleGoodsNumReduce(e) {
    const {
      index
    } = e.currentTarget.dataset
    let cart = this.data.cart
    let num = cart[index].num
    if (num === 1) {
      const res = await showModal({
        content: "您是否要删除？"
      });
      if (res.confirm) {
        cart.splice(index, 1);
        this.setData({
          cart
        })
        wx.setStorageSync("cart", cart)
      }
    } else {
      num--
    }

    cart.forEach((v, i) => {
      i === index ? v.num = num : ''
    })
    this.setMoney(cart)


  },
  handleCheckBox(e) {
    console.log(e)
    const goods_id = e.currentTarget.dataset.id
    const cart = this.data.cart
    let index = cart.findIndex(v => v.goods_id === goods_id);
    // 4 选中状态取反
    cart[index].checked = !cart[index].checked;
    this.setMoney(cart)
  },
  //计算总价格
  setMoney(cart) {
    let allchecked = true
    let totalprice = 0;
    let totalnum = 0;
    cart.forEach(v => {
      if (v.checked) {

        totalprice = totalprice + v.num * v.goods_price;
        totalnum = totalnum + v.num
      } else {
        allchecked = false
      }
    })
    this.setData({
      cart,
      totalnum,
      totalprice,
      allchecked
    })
    wx.setStorageSync("cart", cart)
  },
  //控制全选
  handleAllCheck() {
    const cart = this.data.cart
    cart.forEach(v => v.checked = !v.checked)
    this.setData({
      cart
    })
    this.setMoney(cart)
  },
  //跳转到结算页面
  async handlePay() {
    // 1 判断收货地址
    const {
      address,
      totalnum
    } = this.data;
    if (!address.userName) {
      await showToast({
        title: "您还没有选择收货地址"
      });
      return;
    }
    // 2 判断用户有没有选购商品
    if (totalnum === 0) {
      await showToast({
        title: "您还没有选购商品"
      });
      return;
    }
    // 3 跳转到 支付页面
    wx.navigateTo({
      url: '/pages/pay/index'
    });
  }
})